<template>
  <div class="shopping-cart">

    <!-- 删除按钮 -->
    <el-button v-if="tableData && tableData.length !== 0" class="clear-cart" type="primary" icon="el-icon-delete-solid"
      title="清空购物车" @click="clearCarts" circle></el-button>
    <!-- 头部logo -->
    <div class="product-box">
      <div class="nav-bar">
        <div class="container">
          <router-link to="/MallHome" style="text-decoration: none" title="奶油奶优">
            <!-- <el-image class="logo" style="width: 55px;height: 55px;margin-top: 10px;margin-right: 15px;"
              src="@/assets"></el-image> -->
          </router-link>
          <div style="display: inline-block;position:absolute;top: 15px">
            <h2>我的购物车</h2>
            <div class="tip">
              <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <div class="page-main" v-if="tableData">
      <div class="cart-info" v-if="tableData.length !== 0">
        <el-table ref="cartTable" :data="tableData" tooltip-effect="dark" :highlight-current-row="false"
          style="width: 100%;" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="150" align="center"></el-table-column>
          <el-table-column label="商品名称">
            <template slot-scope="scope">
              <router-link :to="'/MallPurchase?product_id=' + scope.row.product_id" style="text-decoration:none;">
                <div class="product-name">
                  <el-image class="product-img" :src="scope.row.product_url1"></el-image>
                  <span class="name">{{ scope.row.product_name }}</span>
                </div>
              </router-link>
            </template>
          </el-table-column>

          <el-table-column prop="product_specs" label="规格" width="300" align="center">
            <template slot-scope="scope">
              <span style="color: #AA8764;" v-if="JSON.parse(scope.row.product_specs.substring(0,
                scope.row.product_specs.length)).SpecsSize == null">{{ JSON.parse(scope.row.product_specs.substring(0,
    scope.row.product_specs.length)).data_weight }}</span>

              <span v-else style="color: #AA8764;">{{ JSON.parse(scope.row.product_specs.substring(0,
                scope.row.product_specs.length)).SpecsSize
                + ' | '
                + JSON.parse(scope.row.product_specs.substring(0, scope.row.product_specs.length)).defaulteat
                + ' | ' + JSON.parse(scope.row.product_specs.substring(0, scope.row.product_specs.length)
                ).defaultware }}</span>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ JSON.parse(scope.row.product_specs).product_price }}元</span>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="180" align="center">
            <template slot-scope="scope">
              <el-input-number size="small" :min="1" :max="scope.row.product_stock" @change="calculationPrice(scope.row)"
                v-model="scope.row.pay_amount"></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="150" align="center">
            <template slot-scope="scope">
              <span style="color: #ff6700">{{ JSON.parse(scope.row.product_specs).product_price * scope.row.pay_amount
              }}元</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteProduct(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="cart-bar">
          <div class="section-left">
            <router-link to="/MallHome" style="text-decoration: none">
              <span class="to-shop">
                继续购物
              </span>
            </router-link>
            <el-divider direction="vertical"></el-divider>
            <span>
              共
              <span style="color: #FF6700">{{ this.tableData.length }}</span>
              件商品，已选择
              <span style="color: #FF6700">{{ this.selectedData.length }}</span>
              件
            </span>
          </div>
          <div class="section-right">
            <span class="total">
              合计：
              <span style="font-size: 30px">{{ summation }}</span>
              元
            </span>
            <el-tooltip content="请勾选需要结算的商品" v-if="selectedData" :disabled="selectedData.length !== 0" placement="top"
              effect="light">
              <div class="button">
                <el-button type="danger" style="height: 100%;width: 100%" :disabled="selectedData.length === 0"
                  @click="buy">去结算</el-button>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>
      <!-- 未有 -->
      <div v-else class="empty-cart-top">
        <h2>
          您的购物车还是空的！
        </h2>
        <el-button type="success" @click="goShopping">马上去购物</el-button>
      </div>
    </div>


    <!--产生订单-->
    <el-dialog title="订单信息" :visible.sync="orderFormVisible" width="400px" style=" font-size: 2rem;">
      <el-form :model="baseInfo" class="order-form" :rules="baseInfo" ref="order">
        <el-form-item label="收货人:" prop="user_name">
          <el-input v-model="baseInfo.user_name" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="telephone">
          <el-input v-model="baseInfo.telephone" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="收货地址:" prop="user_address" style="position: relative">
          <el-input v-model="baseInfo.user_address"></el-input>
f
        </el-form-item>
        <el-form-item label="预计支付:">
          <el-input v-model="baseInfo.pay_price" disabled style="color:red;">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="createOrder('order')">付 款</el-button>
        <el-button @click="orderFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--产生结算-->
    <el-dialog :visible.sync="setVisible" width="800px" style=" font-size: 3rem;">
      <settle :goods="selectedData"></settle>
    </el-dialog>
  </div>
</template>

<script>
import { showShopcart, updateCart, delShopCart, clearCart, AddOrder, showuser } from '@/api/index'
import settle from '@/components/index/settle.vue';
export default {
  name: 'KodaiProuductCart',
  data () {
    return {
      tableData: [],
      selectedData: [],  //选中的
      orders: [],
      baseInfo: {
        pay_price: 0
      },
      orderFormVisible: false,
      setVisible: false
    };
  },

  mounted () {
    showShopcart().then(res => {
      this.tableData = res.data.data
    })
    showuser().then(res => {
      this.baseInfo = res.data.data[0]
      console.log(res);
    })
  },

  methods: {
    goShopping () {
      this.$router.push({ path: '/MallHome' })
    },
    // 点击清空购物车
    clearCarts () {
      this.$confirm('是否清空选中的商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.selectedData == 0) return this.showMessage.call(this, 'error', '未选择商品!');
        let loading = this.$loading({ lock: true, text: "数据处理中", background: "rgba(255,255,255,0.1)" });
        var cart_ids = []
        this.selectedData.forEach(item => {
          cart_ids.push(item.cart_id)
        })
        clearCart(cart_ids).then(res => {
          loading.close();
          if (res.data.code === 200) {
            this.showMessage.call(this, 'success', '购物车已清空!');
            showShopcart().then(res => {
              this.tableData = res.data.data
            })
          }
        }).catch((err) => { loading.close(); this.showMessage.call(this, 'err', '清空购物车失败!!' + err); })
      }).catch(() => { });
    },
    // 选中
    handleSelectionChange (val) {
      this.selectedData = val;
    },
    // 点击数量
    calculationPrice (row) {
      updateCart({ 'num': row.pay_amount, 'cart_id': row.cart_id })
    },
    // 点击删除单个商品
    deleteProduct (row) {
      this.$confirm('此商品将从购物车中移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row);
        let loading = this.$loading({ lock: true, text: "数据提交中", background: "rgba(255,255,255,0.1)" });
        delShopCart({ 'cart_id': row.cart_id }).then(res => {
          loading.close();
          if (res.data.code === 200) {
            this.$message({ type: 'success', message: '移除成功!' });
            showShopcart().then(res => {
              this.tableData = res.data.data
            })
          }
        }).catch((err) => { loading.close(); this.showMessage.call(this, 'error', '移除失败!' + err); })
      }).catch(() => { });
    },
    // 生成订单
    createOrder () {
      this.orders.length = 0;
      let cartIds = [];
      for (let index = 0, len = this.selectedData.length; index < len; index++) {
        let order = {
          order_no:'O'+this.$getDateNow(),
          product_no: this.selectedData[index].product_no,
          pay_price: JSON.parse(this.selectedData[index].product_specs).product_price * this.selectedData[index].pay_amount,
          product_specs: this.selectedData[index].product_specs,
          pay_amount: this.selectedData[index].pay_amount,
          pay_type: '支付宝',
          order_state: Math.round(Math.random() * 5),
          user_address: this.baseInfo.user_address   //收货地址
        }
        cartIds.push(this.selectedData[index].cart_id);
        this.orders.push(order);
      }
      let loading = this.$loading({ lock: true, text: "订单处理中", background: "rgba(255,255,255,0.1)" });
      AddOrder(this.orders).then(res => {
        loading.close();
        if (res.data.code === 200) {
          clearCart(cartIds).then(res => {
            setTimeout(() => {
              this.$router.go(0)
            }, 2000);
          })
          this.orderFormVisible = false;
          this.setVisible = true
        } else {
          this.showMessage.call(this, 'error', '提交订单失败!' + res.data.msg);
        }
      }).catch((err) => { loading.close(); this.showMessage.call(this, 'error', '提交订单失败!' + err); })
    },
    // 结算
    buy () {
      //总支付金额
      this.baseInfo.pay_price = this.summation;
      if (this.baseInfo.user_name !== null && this.baseInfo.user_name.length === 0) {
        this.baseInfo.user_name = JSON.parse(window.localStorage.getItem('stoken')).roles
      }
      if (this.baseInfo.telephone !== null && this.baseInfo.telephone.length === 0) {
        this.$confirm('检测到您未绑定手机号，快递小哥哥将无法找到您', '提示', {
          confirmButtonText: '现在绑定',
          cancelButtonText: '临时填写',
          type: 'warning'
        }).then(() => { this.$router.push('/personalCenter') }).catch(() => {
          this.orderFormVisible = true;
        });
      } else {
        if (this.baseInfo.telephone == null) {
          this.showMessage.call(this, 'error', '手机号为空!');
          this.$router.push('/personalCenter')
        } else {
          this.orderFormVisible = true;
        }

      }
    }
  },
  computed: {
    summation () {
      var total = 0
      this.selectedData.forEach(item => {
        total += JSON.parse(item.product_specs).product_price * item.pay_amount
      })
      return total
    }
  },
  components: {
    settle
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0px 20px !important;
}

.shopping-cart {
  margin: 0;
  padding: 0;
  background: #F5F5F5;
  user-select: none;
  min-height: 100%;
  min-width: 1226px;

}

.shopping-cart .product-box {
  position: relative;
  z-index: 4;
  background: #fff;
  border-top: 1px solid #e0e0e0;
  border-bottom: 1px solid #e0e0e0;
  -webkit-box-shadow: 0 5px 5px rgba(0, 0, 0, .07);
  box-shadow: 0 5px 5px rgba(0, 0, 0, .07);
}

.shopping-cart .product-box .nav-bar {
  position: relative;
  height: 80px;
  width: 100%;
  margin-top: 0;
  color: #616161;
  border-bottom: 1px solid #c9c9c9;

}

.shopping-cart .nav-bar .container {
  position: relative;
  width: 80%;
  min-width: 1226px;
  margin-right: auto;
  margin-left: auto;
  text-align: left;
}


.shopping-cart .nav-bar .container h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 400;
  line-height: 60px;
  color: #424242;
  display: inline-block;
}

.shopping-cart .nav-bar .container .tip {
  display: inline-block;
  margin-left: 20px;
  font-size: 15px;
  margin-top: 21px;
}

.shopping-cart .nav-bar div span {
  font-size: 12px;
  color: #757575;
}

.shopping-cart .page-main {
  min-height: 65vh;
  padding: 30px 0;
}

.shopping-cart .page-main .cart-info {
  margin: 0 auto;
  width: 80%;
  min-height: 65vh;
  min-width: 1170px;
}

/*表格属性*/
.shopping-cart .el-table-column--selection .cell {
  padding-left: 9px;
}

.shopping-cart .el-table th.gutter {
  display: table-cell !important;
}

.shopping-cart .el-table th {
  height: 70px;
}


.shopping-cart .el-table th .cell {
  text-align: center;
  color: #424242;
}

.shopping-cart .el-table__body td {
  text-align: center;
  color: #424242;
  font-size: 16px;
}

.shopping-cart .cart-info .product-name {
  text-align: left;
  vertical-align: middle;
}

.shopping-cart .cart-info .product-name .product-img {
  width: 80px;
  height: 80px;
  margin: 10px 10px 10px 0;
  vertical-align: middle;
}

.shopping-cart .cart-info .product-name .name {
  font-size: 18px;
  font-weight: 400;
  color: #424242;
  white-space: nowrap;
  overflow: hidden;
  vertical-align: middle;
  display: inline-block;
  max-width: 260px;
  overflow: hidden;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  word-break: break-all;
  text-overflow: ellipsis;
}

.shopping-cart .cart-info .cart-bar {
  position: relative;
  margin: 20px 0;
  width: 100%;
  height: 50px;
  background-color: #fff;
  -webkit-transition: background .3s ease, top .3s ease;
  transition: background .3s ease, top .3s ease;
  line-height: 50px;
}

.shopping-cart .cart-info .cart-bar .section-left {
  position: absolute;
  line-height: 50px;
  margin-left: 32px;
  left: 0;
}

.shopping-cart .cart-info .cart-bar .section-left span {
  font-size: 14px;
  color: #757575
}

.shopping-cart .cart-info .cart-bar .section-left .to-shop:hover {
  color: #ff6700;

}

// 按钮
.shopping-cart .cart-info .cart-bar .section-right {
  position: absolute;
  right: 0;
}

// 总价
.shopping-cart .cart-info .cart-bar .section-right .total {
  position: absolute;
  top: 0;
  right: 170px;
  height: 50px;
  width: 200px;
  text-align: right;
  margin-left: 20px;
  color: #FF6700;
  font-size: 14px;
}

.shopping-cart .cart-info .cart-bar .section-right .button {
  position: absolute;
  top: 0;
  right: 0;
  height: 50px;
  width: 150px;
}

// 购物车为0
.shopping-cart .page-main .empty-cart-top {
  height: 273px;
  padding-left: 50%;
  margin: 65px 0 130px;
  background: url(https://spring-oss.oss-cn-beijing.aliyuncs.com/images/img/cart-empty.png) no-repeat 30% 0;
  color: #b0b0b0;
  overflow: hidden;
  text-align: left;
}

.shopping-cart .page-main .empty-cart-top h2 {
  margin: 70px 0 0 0;
  font-size: 36px;
}

.shopping-cart .page-main .empty-cart-top .el-button {
  margin: 15px 0 0;
  width: 170px;
  height: 46px;
  font-size: 18px;
}

// 删除按钮
.shopping-cart .clear-cart {
  position: fixed;
  width: 60px;
  height: 60px;
  right: 8%;
  bottom: 10%;
  z-index: 9999;
}

.shopping-cart .clear-cart :v-deep .el-button {
  font-size: 40px;
}

//过度效果

// ::v-deep .el-input__inner  {
//   transition: all 0.3s ease;
//   transform: translateY(-10px);
// }
</style>